package com.xky.ui.module.salesManagement;

import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.ui.module.salesManagement.add.AddSalesOrder;
import com.xky.ui.module.salesManagement.delete.DeleteSalesOrder;
import com.xky.ui.module.salesManagement.update.UpdateSalesOrder;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;

/**
 * 销售订单信息管理界面类
 */
public class SalesMassage {

    // 表格组件
    private static JTable table;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color ADD_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color UPDATE_BUTTON_COLOR = new Color(52, 152, 219);
    private static final Color DELETE_BUTTON_COLOR = new Color(231, 76, 60);
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color REFRESH_BUTTON_COLOR = new Color(142, 68, 173);
    private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
    private static final Color HIGHLIGHT_ROW_COLOR = new Color(235, 245, 251);
    private static final Color ALTERNATE_ROW_COLOR = new Color(248, 251, 255);
    
    // 定义字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 26);
    private static final Font SUBTITLE_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
    private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    
    // 订单状态颜色映射
    private static final Map<String, Color> STATUS_COLORS = new HashMap<>();
    static {
        STATUS_COLORS.put("待处理", new Color(230, 126, 34));
        STATUS_COLORS.put("已确认", new Color(41, 128, 185));
        STATUS_COLORS.put("已发货", new Color(46, 204, 113));
        STATUS_COLORS.put("已完成", new Color(39, 174, 96));
        STATUS_COLORS.put("已取消", new Color(231, 76, 60));
    }
    
    // 支付状态颜色映射
    private static final Map<String, Color> PAYMENT_COLORS = new HashMap<>();
    static {
        PAYMENT_COLORS.put("未支付", new Color(192, 57, 43));
        PAYMENT_COLORS.put("部分支付", new Color(243, 156, 18));
        PAYMENT_COLORS.put("已支付", new Color(39, 174, 96));
        PAYMENT_COLORS.put("已退款", new Color(142, 68, 173));
    }
    
    // 状态代码到显示文本的映射
    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    static {
        STATUS_MAP.put("pending", "待处理");
        STATUS_MAP.put("confirmed", "已确认");
        STATUS_MAP.put("shipped", "已发货");
        STATUS_MAP.put("completed", "已完成");
        STATUS_MAP.put("cancelled", "已取消");
    }
    
    private static final Map<String, String> PAYMENT_STATUS_MAP = new HashMap<>();
    static {
        PAYMENT_STATUS_MAP.put("unpaid", "未支付");
        PAYMENT_STATUS_MAP.put("partial", "部分支付");
        PAYMENT_STATUS_MAP.put("paid", "已支付");
        PAYMENT_STATUS_MAP.put("refunded", "已退款");
    }
    
    // 日期时间格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建销售订单信息面板
     * @param refreshAction 刷新操作
     * @return 销售订单信息面板
     */
    public static JPanel createSalesInfoPanel(Runnable refreshAction) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板（标题和按钮）
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("销售订单基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 分割线
        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(1200, 2));
        separator.setBackground(SEPARATOR_COLOR);
        
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel(refreshAction);
        
        // 添加到顶部面板
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(separator, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 表格
        JScrollPane scrollPane = createSalesTable();
        
        // 添加到主面板
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建按钮面板
     * @param refreshAction 刷新操作
     * @return 按钮面板
     */
    private static JPanel createButtonPanel(Runnable refreshAction) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.setBackground(SECONDARY_COLOR);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 创建按钮
        JButton addButton = createStyledButton("添加", BUTTON_COLOR);
        JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
        JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
        JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
        JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);

        // 添加事件监听器
        addButton.addActionListener(e -> {
            new AddSalesOrder();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        deleteButton.addActionListener(e -> {
            if (table.getSelectedRow() != -1) {
                int selectedRow = table.getSelectedRow();
                int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
                new DeleteSalesOrder(orderId);
            } else {
                new DeleteSalesOrder();
            }
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        updateButton.addActionListener(e -> {
            if (table.getSelectedRow() != -1) {
                int selectedRow = table.getSelectedRow();
                int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
                new UpdateSalesOrder(orderId);
            } else {
                new UpdateSalesOrder();
            }
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        queryButton.addActionListener(e -> showSearchDialog());

        refreshButton.addActionListener(e -> {
            SelectSalesOrder.resetSearchStatus();
            if (refreshAction != null) {
                refreshAction.run();
                updateStatusMessage("销售订单数据已刷新");
                
                // 启动自动刷新
                if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
                    autoRefreshTimer.start();
                }
            }
        });

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);

        return buttonPanel;
    }
    
    /**
     * 创建统一风格的按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 按钮对象
     */
    private static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        return button;
    }

    /**
     * 创建销售订单表格
     * @return 包含表格的滚动面板
     */
    public static JScrollPane createSalesTable() {
        // 表格列名
        String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "预计发货日期", "实际发货日期", 
                               "仓库ID", "商品总额", "税额",
                               "折扣金额", "订单总金额", "已付金额", "备注", "创建时间", "更新时间"};

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);

        // 创建表格
        table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        table.getTableHeader().setOpaque(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setAutoCreateRowSorter(true);
        table.setShowGrid(true);
        table.setGridColor(new Color(230, 230, 230));

        // 设置表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(70);
        table.getColumnModel().getColumn(1).setPreferredWidth(100);
        table.getColumnModel().getColumn(2).setPreferredWidth(70);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(120);
        table.getColumnModel().getColumn(5).setPreferredWidth(120);
        table.getColumnModel().getColumn(6).setPreferredWidth(70);
        table.getColumnModel().getColumn(7).setPreferredWidth(100);
        table.getColumnModel().getColumn(8).setPreferredWidth(70);
        table.getColumnModel().getColumn(9).setPreferredWidth(100);
        table.getColumnModel().getColumn(10).setPreferredWidth(130);
        table.getColumnModel().getColumn(11).setPreferredWidth(100);
        table.getColumnModel().getColumn(12).setPreferredWidth(60);
        table.getColumnModel().getColumn(13).setPreferredWidth(120);
        table.getColumnModel().getColumn(14).setPreferredWidth(120);

        // 设置单元格渲染器
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        
        // 对所有列应用居中渲染器，除了备注列
        for (int i = 0; i < columnNames.length; i++) {
            if (i != 14) { // 备注列除外
                table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
            }
        }
        
        // 添加双击打开编辑功能
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow != -1) {
                        int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
                        new UpdateSalesOrder(orderId);
                    }
                }
            }
        });

        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        scrollPane.getViewport().setBackground(Color.WHITE);
        
        return scrollPane;
    }

    /**
     * 更新表格数据
     * @param table 表格
     * @param orderList 销售订单列表
     */
    public static void updateTableData(JTable table, List<SalesOrders> orderList) {
        if (table == null || orderList == null) {
            return;
        }
        
        DefaultTableModel model = (DefaultTableModel) table.getModel();

        // 清空表格中现有的数据
        model.setRowCount(0);

        for (SalesOrders order : orderList) {
            String orderDateStr = order.getOrderDate() != null ? 
                order.getOrderDate().format(DATETIME_FORMATTER) : "";
            String expectedShipDateStr = order.getExpectedShipDate() != null ? 
                order.getExpectedShipDate().format(DATE_FORMATTER) : "";
            String actualShipDateStr = order.getActualShipDate() != null ? 
                order.getActualShipDate().format(DATE_FORMATTER) : "";
            String createdTimeStr = order.getCreatedTime() != null ? 
                order.getCreatedTime().format(DATETIME_FORMATTER) : "";
            String updatedTimeStr = order.getUpdatedTime() != null ? 
                order.getUpdatedTime().format(DATETIME_FORMATTER) : "";
                
            model.addRow(new Object[]{
                order.getOrderId(),
                order.getOrderNumber(),
                order.getCustomerId(),
                    orderDateStr,
                    expectedShipDateStr,
                    actualShipDateStr,
                order.getWarehouseId(),
                order.getSubtotal(),
                order.getTaxAmount(),
                order.getDiscountAmount(),
                order.getTotalAmount(),
                order.getPaidAmount(),
                order.getNotes(),
                    createdTimeStr,
                    updatedTimeStr
            });
        }

        // 触发表格数据刷新
        model.fireTableDataChanged();
    }
    
    /**
     * 显示查询对话框
     */
    private static void showSearchDialog() {
        // 创建对话框
        JDialog searchDialog = new JDialog((Frame)null, "查询销售订单", true);
        searchDialog.setSize(900, 550);
        searchDialog.setLocationRelativeTo(null);
        searchDialog.setLayout(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
        topPanel.setBackground(SECONDARY_COLOR);

        // 创建单选按钮组
        JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        radioPanel.setOpaque(false);
        
        ButtonGroup buttonGroup = new ButtonGroup();
        JRadioButton idRadio = new JRadioButton("按订单ID查询", true);
        JRadioButton numberRadio = new JRadioButton("按订单编号查询");
        JRadioButton customerRadio = new JRadioButton("按客户ID查询");
        JRadioButton keywordRadio = new JRadioButton("关键字查询");
        
        idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        numberRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        customerRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        keywordRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        
        idRadio.setOpaque(false);
        numberRadio.setOpaque(false);
        customerRadio.setOpaque(false);
        keywordRadio.setOpaque(false);

        buttonGroup.add(idRadio);
        buttonGroup.add(numberRadio);
        buttonGroup.add(customerRadio);
        buttonGroup.add(keywordRadio);

        radioPanel.add(idRadio);
        radioPanel.add(numberRadio);
        radioPanel.add(customerRadio);
        radioPanel.add(keywordRadio);

        topPanel.add(radioPanel, BorderLayout.NORTH);

        // 创建搜索条件面板
        JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
        searchPanel.setOpaque(false);
        
        JLabel searchLabel = new JLabel("查询条件: ");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        
        JTextField searchField = new JTextField(20);
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        searchField.setPreferredSize(new Dimension(200, 30));
        
        JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);

        JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
        searchFieldPanel.setOpaque(false);
        searchFieldPanel.add(searchLabel, BorderLayout.WEST);
        searchFieldPanel.add(searchField, BorderLayout.CENTER);
        searchFieldPanel.add(searchButton, BorderLayout.EAST);
        searchPanel.add(searchFieldPanel, BorderLayout.NORTH);

        // 添加提示信息
        JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 订单编号/ 客户ID/ 订单状态/ 支付状态/ 备注");
        tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
        tipLabel.setForeground(Color.GRAY);
        tipLabel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
        searchPanel.add(tipLabel, BorderLayout.CENTER);

        topPanel.add(searchPanel, BorderLayout.CENTER);
        searchDialog.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "订单状态", "支付状态", "订单总金额"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable resultTable = new JTable(tableModel);
        resultTable.setRowHeight(30);
        resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
        resultTable.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        resultTable.getTableHeader().setOpaque(true);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setShowGrid(true);
        resultTable.setGridColor(new Color(230, 230, 230));

        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        scrollPane.getViewport().setBackground(Color.WHITE);
        searchDialog.add(scrollPane, BorderLayout.CENTER);

        // 创建底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        buttonPanel.setBackground(SECONDARY_COLOR);
        
        JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
        JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
        
        buttonPanel.add(selectButton);
        buttonPanel.add(cancelButton);
        searchDialog.add(buttonPanel, BorderLayout.SOUTH);

        // 设置按钮动作
        searchButton.addActionListener(e -> {
            String searchText = searchField.getText().trim();
            if (searchText.isEmpty()) {
                JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            List<SalesOrders> resultList = new ArrayList<>();

            try {
                if (idRadio.isSelected()) {
                    try {
                        int id = Integer.parseInt(searchText);
                        List<SalesOrders> orders = SelectSalesOrder.selectById(id);
                        if (orders != null && !orders.isEmpty()) {
                            resultList.addAll(orders);
                        }
                                } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else if (numberRadio.isSelected()) {
                    // 按订单编号查询
                    List<SalesOrders> orders = SelectSalesOrder.selectByOrderNumber(searchText);
                    if (orders != null && !orders.isEmpty()) {
                        resultList.addAll(orders);
                    }
                } else if (customerRadio.isSelected()) {
                    // 按客户ID查询
                    try {
                        int customerId = Integer.parseInt(searchText);
                        List<SalesOrders> orders = SelectSalesOrder.selectByCustomerId(customerId);
                        if (orders != null && !orders.isEmpty()) {
                            resultList.addAll(orders);
                        }
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(searchDialog, "客户ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else if (keywordRadio.isSelected()) {
                    // 关键字查询
                    List<SalesOrders> orders = SelectSalesOrder.searchByKeyword(searchText);
                    if (orders != null && !orders.isEmpty()) {
                        resultList.addAll(orders);
                    }
                }

                // 更新表格数据
                tableModel.setRowCount(0);

                if (!resultList.isEmpty()) {
                    for (SalesOrders order : resultList) {
                        String orderDateStr = order.getOrderDate() != null ? 
                            order.getOrderDate().format(DATETIME_FORMATTER) : "";
                            
                        tableModel.addRow(new Object[]{
                                order.getOrderId(),
                                order.getOrderNumber(),
                                order.getCustomerId(),
                                orderDateStr,
                                STATUS_MAP.get(order.getOrderStatus()),
                                PAYMENT_STATUS_MAP.get(order.getPaymentStatus()),
                                order.getTotalAmount()
                        });
                    }
                } else {
                    JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        });

        cancelButton.addActionListener(e -> searchDialog.dispose());

        selectButton.addActionListener(e -> {
            int selectedRow = resultTable.getSelectedRow();
            if (selectedRow >= 0) {
                // 获取选中的行数据
                int orderId = (int) tableModel.getValueAt(selectedRow, 0);

                // 获取选中的订单数据
                List<SalesOrders> orderList = SelectSalesOrder.selectById(orderId);

                if (!orderList.isEmpty()) {
                    // 清空主表格并只显示选中的订单
                    updateTableData(table, orderList);

                    // 停止自动刷新
                    if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
                        autoRefreshTimer.stop();
                    }

                    // 更新状态消息
                    updateStatusMessage("已选择订单ID: " + orderId);
                }

                searchDialog.dispose();
            } else {
                JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // 设置回车键触发搜索按钮
        searchDialog.getRootPane().setDefaultButton(searchButton);
        
        // 显示对话框
        searchDialog.setVisible(true);
    }
} 